package org.example.controller;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

@RestController
public class ExcelExportController {

    @GetMapping("/export/excel-with-image")
    public ResponseEntity<byte[]> exportExcelWithImage() throws IOException {
        // 创建一个新的工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet("Sheet1");

        // 创建一些示例数据
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("Name");
        headerRow.createCell(1).setCellValue("Image");

        // 添加一些示例数据行
        Row dataRow = sheet.createRow(1);
        dataRow.createCell(0).setCellValue("Sample Name");

        // 读取图片
        Resource resource = new ClassPathResource("image/image.png"); // 确保图片在classpath下
        try (InputStream inputStream = resource.getInputStream()) {
            BufferedImage image = ImageIO.read(inputStream);

            // 将图片添加到工作簿中
            int pictureIdx = workbook.addPicture(inputStream, Workbook.PICTURE_TYPE_PNG);

            // 创建绘图对象
            XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();

            // 创建锚点，设置图片插入的位置
            XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0,
                    dataRow.getRowNum(), dataRow.getRowNum() + 1, // 图片开始的行和结束的行（这里设置为同一行）
                    1, 2); // 图片开始的列和结束的列（跨两列）

            // 插入图片
            drawing.createPicture(anchor, pictureIdx);

            // 调整图片大小（可选，根据需要调整）
            // 这里没有直接的方法调整大小，但你可以通过调整锚点位置来间接实现
        }

        // 将工作簿写入字节数组输出流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        workbook.write(byteArrayOutputStream);
        workbook.close();

        // 准备响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=excel-with-image.xlsx");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        // 创建响应实体
        return new ResponseEntity<>(byteArrayOutputStream.toByteArray(), headers, HttpStatus.OK);
    }
}